﻿using System;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using Microsoft.DirectX.DirectSound;

namespace CC.Yacht.Windows.Forms
{
    public class SoundPlayer : IDisposable
    {
        #region Constructor
        public SoundPlayer(Control owner)
        {
            _Device = new Device();
            _Device.SetCooperativeLevel(owner, CooperativeLevel.Normal);
        }

        ~SoundPlayer()
        {
            Dispose();
        }
        #endregion

        #region Private Fields
        private Device _Device;
        private BufferDescription _BufferDescription = new BufferDescription { ControlEffects = false };
        #endregion

        #region Private Methods
        private static void CleanBuffer(object buffer)
        {
            SecondaryBuffer secondaryBuffer = buffer as SecondaryBuffer;

            if (secondaryBuffer != null)
            {
                while (secondaryBuffer.Status.Playing)
                {
                    Thread.Sleep(100);
                }

                secondaryBuffer.Dispose();
            }
        }
        #endregion

        #region Public Methods
        public void Dispose()
        {
            if (_BufferDescription != null)
            {
                _BufferDescription.Dispose();
                _BufferDescription = null;
            }

            if (_Device != null)
            {
                _Device.Dispose();
                _Device = null;
            }
        }

        public void Play(Stream stream)
        {
            SecondaryBuffer secondaryBuffer = new SecondaryBuffer(stream, _BufferDescription, _Device);
            secondaryBuffer.Play(0, BufferPlayFlags.Default);
            ThreadPool.QueueUserWorkItem(CleanBuffer, secondaryBuffer); //NOTE: Is this the best way to clean up resources? Worried about too many threads getting launched. Could always switch to a single thread + dispose ThreadSafeQueue ...
        }
        #endregion
    }
}
